﻿using Simple.Services.System.Notice.Model;
using Simple.Services.System.User.Models;

namespace Simple.Services.System.Notice
{
    public class NoticeService
    {
        private readonly SimpleDbContext _context; 
        private readonly ICurrentUserService _currentUser;
        private readonly CacheService _cacheService;
        public NoticeService(SimpleDbContext context, ICurrentUserService currentUser, CacheService cacheService)
        {
            _context = context;
            _currentUser = currentUser;
            _cacheService = cacheService;
        }

        public async Task<PageExtendResultModel<NoticeModel>> GetPageAsync(NoticePageInputModel input)
        {
            var result = new PageExtendResultModel<NoticeModel>();
            var query = _context.Set<SysNotice>().AsQueryable().Where(s => s.IsOriginal == input.IsOnlySend && s.Receiver == _currentUser.UserId);

            // 根据条件查询
            if (input.IsRead.HasValue)
            {
                query = query.Where(u => u.IsRead == input.IsRead);
            }
            if (!string.IsNullOrEmpty(input.Name))
            {
                query = query.Where(u => EF.Functions.Like(u.Title, $"%{input.Name}%"));
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();
            result.TotalQuantity = _context.Set<SysNotice>().AsQueryable().Where(s => s.IsOriginal == false && s.Receiver == _currentUser.UserId  && s.IsRead == false).Count();
            // 分页查询
            query = query.OrderByDescending(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var users = await query.ToListAsync();
            result.Rows = MapperHelper.Map<List<NoticeModel>>(users);

            result.SetPage(input);
            result.CountTotalPage();
            return result;
        }

        public async Task<bool> ReadNotice(Guid noticeId)
        {
            var notice = await _context.Set<SysNotice>().FirstOrDefaultAsync(s => s.Id == noticeId);
            if (notice != null)
            {
                notice.IsRead = true;
                _context.Update(notice);
                await _context.SaveChangesAsync();
                if (!notice.IsSend)
                {
                    await _cacheService.RemoveCacheAsync(_cacheService.GetKey(CacheKeyConst.NoticeMessage, notice.Id.ToString()));
                }
            }
            return true;
        }

        public async Task<int> DeleteAsync(Guid noticeId)
        {
            var notice = await _context.Set<SysNotice>().FirstOrDefaultAsync(s => s.Id == noticeId);
            if (notice != null)
            {
                _context.RemoveRange(notice);
                return await _context.SaveChangesAsync();
            }
            return 0;
        }

        public async Task<Guid> AddNoticeAsync(NoticeInputModel model)
        {
            if (model == null)
            {
                throw AppResultException.Status400BadRequest("参数错误");
            }

            /*            if (model.SendTime.HasValue && model.SendTime.Value.Date < DateTime.Now.Date)
                        {
                            throw AppResultException.Status400BadRequest($"发送时间不能小于当前服务器时间[{DateTime.Now.ToString("yyyy-MM-dd")}]");
                        }
            */
            var notice = new SysNotice
            {
                DepartmentId = model.OrganizationId,
                ClassId = model.ClassesId,
                SendTime = model.SendTime ?? DateTime.Now,
                Content = model.Content,
                Title = model.Title,
                IsOriginal = true,
                IsRead = true,
                IsSend = false,
                Receiver = _currentUser.UserId,
                SendUserName = _currentUser.UserName,
                Url = string.Empty,
            };
            var entity = await _context.AddAsync(notice);
            await _context.SaveChangesAsync();
            if (notice.SendTime == null)
            {
                notice.SendTime = DateTime.Now;
            }
            await _cacheService.SetCacheItemAsync<SysNotice>(_cacheService.GetKey(CacheKeyConst.NoticeMessage, notice.Id.ToString()), notice);
            return entity.Entity.Id;
        }
    }
}
